/***************添加分享出现的模态框***************/
let model_share = function (type) {
    this.scrollPhoto = getClass("model-scroll-photo")[0];
    this.timer_model = null;
};
model_share.prototype.getModel = function (type) {
    let that = this;
    if (type === "addShare") {
        that.addShare();
    } else if (type === "share") {
    }
};
//分享框显示
model_share.prototype.addShare = function () {
    let that = this;
    getClass("cont-inner addShare")[0].onclick = function () {
        that.modelShow("block");
        that.scrollPhoto.children[0].style.left = "20px";   //  初始化添加图片栏的长度
    };
    getClass("model-addShare-wrapper")[0].onclick = function () {
        that.modelShow("block");
        that.scrollPhoto.children[0].style.left = "20px";   //  初始化添加图片栏的长度
    };
    getClass("model-addShare-wrapper")[0].onclick = function () {
        that.modelShow("none");
    }
};
//模态框出现和消失
model_share.prototype.modelShow = function (type) {
    if (loginUserIsShare === 0) {
        layer.msg('你被禁止分享', {time: 2000});
        return null;
    }

    if (type === "block") {
        getClass("model-addShare-wrapper")[0].style.display = "block";
        if (detectMob()) {
            getClass("model-addShare")[0].style.top = "0%";
        } else {
            getClass("model-addShare")[0].style.top = "50%";
        }
    } else if (type === "none") {
        this.clearContent();
        getClass("model-addShare-wrapper")[0].style.display = "none";
        getClass("model-addShare")[0].style.top = "-150%";
    }
};
model_share.prototype.addPhoto = function () {
    let that = this;

    function addNode(data) {
        let leftOfNode = parseInt(that.scrollPhoto.children[that.scrollPhoto.children.length - 1].style.left);
        console.log(leftOfNode);
        //新建节点
        let node = document.createElement("div");
        node.className = "model-camera-wrapper";
        node.innerHTML = '<div class="model-camera"><div class="model-camera-imgNode"><img src="' + data.obj.thumbUrl + '" id="' + data.obj.imageId + 'imageId"></div>' + ' <span class="model-camera-exchange"><i class="fa fa-exchange"></i></span><span class="model-camera-close"><i class="fa fa-close"></i></span></div>';
        node.style.left = leftOfNode + "px"; //确定长度
        that.scrollPhoto.children[that.scrollPhoto.children.length - 1].style.left = (leftOfNode + 135) + "px";
        that.scrollPhoto.style.width = (that.scrollPhoto.children.length + 1) * 135 + 40 + "px";
        that.scrollPhoto.insertBefore(node, that.scrollPhoto.children[that.scrollPhoto.children.length - 1]);
        node.getElementsByTagName("span")[1].onclick = function () {
            //私有：点击删除图片时的图片删除
            that._photoDelete(node);
        };
        //自适应
        if (510 < that.scrollPhoto.offsetWidth) {
            getClass("model-scroll")[0].style.marginBottom = -( getClass("model-scroll")[0].offsetHeight - getClass("model-scroll")[0].clientHeight) + "px";
        } else {
            getClass("model-scroll")[0].style.marginBottom = "0"
        }
        getClass("model-scroll")[0].scrollLeft = parseInt(that.scrollPhoto.style.width);
        that._shift();
    }

    getClass("model-photo-input")[0].onclick = function () {
        that.upDatePhoto(this, addNode);
    };

};
//点击删除图片时的图片删除
model_share.prototype._photoDelete = function (node) {
    let leftWidth = parseInt(node.style.left);
    for (let i = 0, flag = 0; i < this.scrollPhoto.children.length; i++) {
        if (leftWidth < parseInt(this.scrollPhoto.children[i].style.left) && node !== this.scrollPhoto.children[i]) {
            this.scrollPhoto.children[i].style.left = parseInt(this.scrollPhoto.children[i].style.left) - 135 + "px";
        }
        else if (node === this.scrollPhoto.children[i]) {
            this.scrollPhoto.removeChild(node);
            i--;
        }
    }
    this.scrollPhoto.style.width = (this.scrollPhoto.children.length) * 135 + 40 + "px";
    //自适应
    if (510 < this.scrollPhoto.offsetWidth) {
        getClass("model-scroll")[0].style.marginBottom = -( getClass("model-scroll")[0].offsetHeight - getClass("model-scroll")[0].clientHeight) + "px";
    } else {
        getClass("model-scroll")[0].style.marginBottom = "0"
    }
};
//图片移动监听函数
model_share.prototype._shift = function () {
    let that = this;
    let changePare = getClass("model-camera-exchange");
    //图片个数减一的长度
    for (let i = 0; i < changePare.length; i++) {
        let point = changePare[i];
        point.ondragenter = function (event) {
            event.preventDefault();
        };
        point.ondragover = function (event) {
            event.preventDefault();
        };
        point.onmousedown = function (event) {
            event = window.event || event;
            let node = point.parentNode.parentNode;
            node.style.zIndex = 1;
            let nodeClientX = event.clientX - parseInt(node.style.left);//60为节点的大小的一半
            let leftPoint = parseInt(node.style.left);
            let min;
            this.onmousemove = function (e) {
                let pareNode = this.parentNode.parentNode;
                pareNode.style.left = e.clientX - nodeClientX + "px";
                pareNode.style.top = "0px";
                min = that._checkNode(pareNode);
                leftPoint = parseInt(node.style.left);
                if (min !== null) {
                    if (min.direct > 0) {
                        min.minNode.style.left = parseInt(min.minNode.style.left) - 135 + "px";
                    }

                    if (min.direct < 0) {
                        min.minNode.style.left = parseInt(min.minNode.style.left) + 135 + "px";
                    }
                }

            };
            this.onmouseout = function (event) {
                let pareNode = this.parentNode.parentNode;
                let leftLen = parseInt(node.style.left);
                let num = Math.round((leftLen - 20) / 135);
                let dir = that._checkNode(pareNode);
                let line = 20 + num * 135;
                if (dir.directToCheck > 0) {
                    if (line >= parseInt(dir.minNode.style.left) - 60) {
                        pareNode.style.left = parseInt(dir.minNode.style.left) - 135 + "px";
                    }
                    pareNode.style.left = line + "px";
                } else {
                    if (line <= parseInt(dir.minNode.style.left) + 60) {
                        pareNode.style.left = parseInt(dir.minNode.style.left) + 135 + "px";
                    }
                    pareNode.style.left = line + "px";
                    if (parseInt(pareNode.style.left) >= parseInt(that.scrollPhoto.children[that.scrollPhoto.children.length - 1].style.left)) {
                        pareNode.style.left = parseInt(that.scrollPhoto.children[that.scrollPhoto.children.length - 1].style.left) - 135 + "px";
                    }
                }
                console.log(that._checkNode(pareNode));
                pareNode.style.zIndex = 0;
                this.onmousemove = null;
                this.onmouseup = null;
            }
        }
    }
};
model_share.prototype._checkNode = function (node) {
    let nearNode;
    let array = [];
    //查找最小点
    let getMinLength = function (array, aim) {
        let min = 99999;
        let minNode = null;
        for (let i = 0; i < array.length - 1; i++) {
            if (array[i] !== aim) {
                let len = Math.abs(parseInt(array[i].style.left) - parseInt(aim.style.left));
                if (min > len) {
                    min = len;
                    minNode = array[i];
                }
            }
        }
        if (Math.abs(parseInt(minNode.style.left) - parseInt(aim.style.left)) < 60 && minNode !== array[array.length - 1]) {
            return {
                direct: parseInt(minNode.style.left) - parseInt(aim.style.left),
                minNode: minNode,
                directToCheck: parseInt(minNode.style.left) - parseInt(aim.style.left)
            }
        } else {
            return {
                direct: null,
                minNode: minNode,
                directToCheck: parseInt(minNode.style.left) - parseInt(aim.style.left)
            }
        }

    };
    return getMinLength(this.scrollPhoto.children, node);
};
//输入文字框显示
model_share.prototype.textareaScroll = function () {
    getClass("textarea-share")[0].oninput = function () {
        if (this.clientHeight < this.scrollHeight) {
            this.style.paddingRight = 20 - (this.offsetWidth - this.clientWidth) + 3 + "px";
        } else {
            this.style.paddingRight = 20 + "px"
        }
    }
};
//滚动私有还是共有
model_share.prototype.getAuth = function () {
    getClass("model-authority")[0].onclick = function () {
        if (getClass("model-authority-roll")[0].style.right === "" || getClass("model-authority-roll")[0].style.right === "1px") {
            getClass("model-authority-public")[0].style.display = "none";
            getClass("model-authority-private")[0].style.display = "block";
            getClass("model-authority-roll")[0].style.right = 35 + "px";
        } else {
            getClass("model-authority-public")[0].style.display = "block";
            getClass("model-authority-private")[0].style.display = "none";
            getClass("model-authority-roll")[0].style.right = 1 + "px";
        }
    }
};
//取消打开添加框
model_share.prototype.cancelOpen = function () {
    let that = this;
    getClass("model-close")[0].onclick = function () {
        that.modelShow("none");
    };
    getClass("cancel-open")[0].onclick = function () {
        that.modelShow("none");
    }
};

//上传图片方法
model_share.prototype.upDatePhoto = function (node, func) {
    let that = this;
    node.onchange = function () {
        getClass("photoUpdate-form")[0].submit = function () {
            if (this.children[0].value) {
                $(this).ajaxSubmit(function (data) {
                    console.log(data);
                    func(data);
                });
            }
            return false;
        };
        getClass("photoUpdate-form")[0].submit();
    };
};
//根据距离确定图片的距离,冒泡排序算法
model_share.prototype.sortNode = function () {
    let array = [], arrayImg = [],
        flag, temp;
    //得到图片节点对象数组
    for (let i = 0; i < this.scrollPhoto.children.length - 1; i++) {
        array.push(this.scrollPhoto.children[i])
    }
    //得到排序后的节点对象
    for (let i = 0; i < array.length; i++) {
        flag = 0;
        for (let j = 0; j < array.length - 1 - i; j++) {
            if (parseInt(array[j].style.left) > parseInt(array[j + 1].style.left)) {
                temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
                flag = 1;
            }
        }
        if (flag === 0) {
            break;
        }
    }
    //得到排序后图片节点对象图片链接
    for (let i = 0; i < array.length; i++) {
        arrayImg.push(parseInt(array[i].getElementsByTagName("img")[0].id));
    }
    return arrayImg;
};
model_share.prototype._ajax_all = function (data, url, type, fn) {
    let basePath = getRootPath_web();
    return new Promise((resolve, reject) => {
        $.ajax({
            type: type,
            url: basePath + url,
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify(data),
            success: function (data) {
                if (fn) {
                    fn(data);
                }
                resolve(data);
            },
            error: function (data) {
                reject("发生错误");
                throw new error("发生错误");
            }
        });
    })
};
model_share.prototype.checkKeyword = function (text, fn) {
    let url = "/share/check",
        data_send = {
            content: text
        },
        method = "POST";
    ajax_base(data_send, url, method, "notJson").then(function (dataFlag) {
        if (dataFlag.obj.length > 0) {
            let sensitiveWord = '包含禁止的关键字：'
            for (let i = 0; i < dataFlag.obj.length; i++) {
                if (i === 0) {
                    sensitiveWord += dataFlag.obj[i]
                } else {
                    sensitiveWord += '，' + dataFlag.obj[i]
                }
            }
            layer.msg(sensitiveWord, {time: 3000});
            setTimeout(function () {
                return null;
            }, 3000);
        } else {
            fn()
        }
    })
};
model_share.prototype.updateShare = function () {
    let that = this;
    //基础配置
    let url = "/share/new";
    let type = "POST";
    let data;
    getClass("shareAdd-sure-send")[0].onclick = function () {
        that.sortNode();
        let text = getClass("textarea-share")[0].value;
        let arrayImg = that.sortNode();
        data = {
            "imageIds": arrayImg,
            "content": text,
            "atIds": null,
            "userId": loginUserId,
            "sourceId": null,
            "hide": false
        };
        if (text === "") {
            layer.msg('输入内容为空', {time: 2000});
            return;
        }
        if (arrayImg.length === 0) {
            layer.msg('图片未上传', {time: 2000});
            return;
        }
        that.checkKeyword(text, function () {
            that._ajax_all(data, url, type).then(function (data) {
                if (data) {
                    layer.msg('上传成功', {time: 1000});
                    setTimeout(function () {
                        that.clearContent();
                        that.modelShow("none");
                        window.open(getRootPath_web() + '/share/index', '_self')
                    }, 1000);
                } else {
                    /**********错误处理*******/
                    console.log(data);
                }
            });
        })
    }
};
//清除模态框内容
model_share.prototype.clearContent = function () {
    for (let i = this.scrollPhoto.children.length - 2; i >= 0; i--) {
        this.scrollPhoto.removeChild(this.scrollPhoto.children[i]);
    }
    this.scrollPhoto.parentNode.style.marginBottom = "0px";
    this.scrollPhoto.style.width = this.scrollPhoto.parentNode.clientWidth + "px";
    getClass("textarea-share")[0].value = "";
};
model_share.prototype.check = function () {
    let that = this;
    if (document.querySelector(".model-addShare")) {
        this.timer_model = setInterval(function () {
            if (getClass("cont-inner addShare")[0]) {
                clearInterval(that.timer_model);
                that.getModel("addShare");
                that.textareaScroll();
                that.addPhoto();
                that.getAuth();
                that.cancelOpen();
                that.updateShare();
                return null;
            }
        }, 500)
    }
};
let model_Show = new model_share();
model_Show.check();

/******************普通模态框显示****************/
let ModelNormal = function () {
    this.pareNode = document.querySelector(".model-normal");
    this.fadeModel = document.querySelector(".model-normal-wrapper");
};
ModelNormal.prototype.whetherShow = function (flag) {
    if (flag) {
        this.fadeModel.style.display = "block";
        this.pareNode.style.top = "50%";
    } else {
        this.fadeModel.style.display = "none";
        this.pareNode.style.top = "-150%";
        this.pareNode.querySelector(".textarea-share").value = "";
    }
};
ModelNormal.prototype.setText = function (typeText, reasonText) {
    this.pareNode.querySelectorAll(".model-map span")[1].innerText = " " + typeText;
    this.pareNode.querySelector(".textarea-share").setAttribute("placeholder", reasonText);
};
ModelNormal.prototype.setShow = function (kindString) {
    let that = this;
    that.pareNode.querySelector(".model-close").onclick = function () {
        that.whetherShow(false);
    };
    that.pareNode.querySelector(".cancel-open").onclick = function () {
        that.whetherShow(false);
    };
    that.pareNode.querySelector(".shareAdd-sure-send").onclick = function () {
        let text = that.pareNode.querySelector(".textarea-share").value;
        if (text === "") {
            layer.msg('内容为空', {time: 800});
            return;
        }
        that.ajax_send(text).then(function (data) {
            if (data && data.success) {
                layer.msg(kindString + '成功', {time: 1000});
                setTimeout(function () {
                    that.pareNode.querySelector(".textarea-share").value = "";
                    that.whetherShow(false);
                }, 1000);
            } else {
                layer.msg(kindString + '失败，请重试', {time: 1000});
            }
        });
    };
};

ModelNormal.prototype.setDisplay = function (kindString) {
    this.whetherShow(true);
    this.setShow(kindString);
};
//用于重写的ajax方法
ModelNormal.prototype.ajax_send = function (text) {
    let data = {
            imageIds: null,
            content: text,
            atIds: null,
            userId: 1,
            sourceId: loginUserId,
            hide: false
        },
        url = "/share/new",
        method = "POST";
    return ajax_base(data, url, method, "Json");
};